package config

import (
	"embed"
	"fmt"

	//"gopkg.in/yaml.v2"
	"go.uber.org/zap"
	//"io/ioutil"
	//log "hms/util/logger"
	"log"

	"gitee.com/tgodfather/misc/config"
	"gitee.com/tgodfather/misc/logger"
)

//go:embed rs
var efs embed.FS

type HttpRouteSetting struct {
	Selector string `yaml:"selector"`
	Method   string `yaml:"method"`
	Path     string `yaml:"path"`
	Party    string `yaml:"party"`
}

//type  HttpRouteConfig struct {
//	route []HttpRouteSetting  `yaml:"route"`
//}

type ServiceConfig struct {
	ID            string `yaml:"id"`
	ServiceType   string `yaml:"servertype"`
	ServicePrefix string `yaml:"serverprefix"`
	ServiceName   string `yaml:"servername"`
	//ServiceVersion  string `yaml:"server_version"`
	ServerAddress   string `yaml:"serveraddress"`
	ServerAdvertise string `yaml:"serveradvertise"`
	RegistryType    string `yaml:"registrytype"`
	RegistryAddress string `yaml:"registryaddress"`
	//BrokerType      string `yaml:"broker_type"`
	//BrokerAddress   string `yaml:"broker_address"`
	//AlgoType string `yaml:"algo_type"`
	//AlgoId   string `yaml:"algo_id"`
	//HttpRouteFile    string  `yaml:"http_route_file"`
	Routes []HttpRouteSetting `yaml:"routes"`
	Params map[string]string  `yaml:"params"`
}

var serviceCfg = &ServiceConfig{}

func (sc *ServiceConfig) GetParam(key string) (string, bool) {
	value, ok := sc.Params[key]
	return value, ok
	//return "", false
}

//遍历参数,并执行操作处理函数
//函数 返回true 表示 退出循环
func (sc *ServiceConfig) WalkParams(f func(key string, value string) bool) {
	for k, v := range sc.Params {
		bQuit := f(k, v)
		if bQuit {
			break
		}
	}
	//f("", "")
}

func LoadConfig() *ServiceConfig {

	//需要保证只进来一次

	//暂时在此进行log初始化
	logcfg := &logger.LogConfig{
		ConsoleEnable: true,
		Filename:      "./log/api.log",
		MaxSize:       100,
		MaxBackups:    7,
		MaxAge:        30,
		Zap:           zap.NewProductionConfig(),
	}
	logger := logger.NewLogger("api", logcfg, true)
	log.SetOutput(logger)

	content, err := efs.ReadFile("rs/def.yaml")
	if nil == err {
		//log.Println("content", string(content))
	} else {
		log.Println(err)
	}

	vc, err := config.NewVConfig(config.WithDefConfigData(content, "yaml"))

	log.Println("=write config", err, vc.WriteConfigAs("test1.yaml"))

	if uErr := vc.Unmarshal(serviceCfg); nil != uErr {
		log.Println(uErr)
	} else {
		//log.Println("After Unmarshal 1", serviceCfg)
	}

	if rErr := vc.ReadConfigFile(config.WithConfigName("config"), config.WithConfigType("yaml")); nil != rErr {
		log.Println(rErr)
	}
	if uErr := vc.Unmarshal(serviceCfg); nil != uErr {
		log.Println(uErr)
	} else {
		//log.Println("After Unmarshal 2", serviceCfg)
	}

	//vc.Unmarshal(serviceCfg)

	//log.Println("== write config", vc.WriteConfigAs("test2.yaml"))

	//如果 没有设置serviceCfg.ServiceName，自己组装服务名
	if 0 >= len(serviceCfg.ServiceName) {
		serviceCfg.ServiceName = fmt.Sprintf("%s.%s",
			"hms",
			serviceCfg.ID)
	}

	logger.Info("== Load config ", zap.Reflect("serviceCfg", serviceCfg))
	return serviceCfg
}

func GetConfig() *ServiceConfig {
	return serviceCfg
}
